<?php

namespace app\common\model\xiluhouse;

use think\Model;
use traits\model\SoftDelete;

class AppointLog extends Base
{

    use SoftDelete;



    // 表名
    protected $name = 'xiluhouse_appoint_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'can_house_state_arr', //可以选择的状态
        'house_state_text',
        'audit_state_text',
        'house_search_roomnum_ids_text',
        'total_price_text',
        'mobile_text',
        'type_text',
        'subscribe_type_text',
        'state_text',
        'distributetime_text',
        'updatetime_text',
        'gender_text'
    ];
    public function getDistributetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['distributetime']) ? $data['distributetime'] : '');
        return $value ? date('Y/m/d H:i', $value) : '';
    }
    public function getUpdatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['updatetime']) ? $data['updatetime'] : '');
        return $value ? date('Y-m-d H:i', $value) : '';
    }
    public function getCanHouseStateArrAttr($value, $data)
    {
        // 购房状态:0=无意向,1=待看房,2=已看房,3=已付订,4=已签约,5=已款清,6=放弃客户
        $arr = [];
        switch ($data['house_state']) {
            case 0:
                # 无意向
                $arr = [
                    1 => '待看房(已分配)',
                ];
                break;
            case 1:
                # 待看房(已分配)
                $arr = [
                    1 => '待看房(已分配)',
                    2 => '已看房',
                    0 => '无意向',
                    6 => '放弃客户',
                ];
                break;
            case 2:
                # 已看房
                $arr = [
                    2 => '已看房',
                    3 => '已付订',
                    0 => '无意向',
                    6 => '放弃客户',
                ];
                break;
            case 3:
                # 已付订
                $arr = [
                    4 => '已签约',
                    0 => '无意向',
                    6 => '放弃客户',
                ];
                break;
            case 4:
                # 已签约
                $arr = [
                    5 => '已款清',
                    0 => '无意向',
                    6 => '放弃客户',
                ];
                break;
            case 5:
                # 已款清
                $arr = [];
                break;
            case 6:
                # 放弃客户
                $arr = [
                    1 => '待看房(已分配)',
                ];
                break;
            default:
                # code...
                break;
        }
        return $arr;
    }
    public function getTotalPriceTextAttr($value, $data)
    {
        $min_total_price = $data['min_total_price'];
        $max_total_price = $data['max_total_price'];
        $text = '';
        if ($max_total_price != 0) {
            if ($max_total_price == -1) {
                $text = '大于' . $min_total_price . '万元';
            } else {
                $text = $min_total_price . '-' . $max_total_price . '万元';
            }
        }
        return $text;
    }

    public function getHouseSearchRoomnumIdsTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['house_search_roomnum_ids']) ? $data['house_search_roomnum_ids'] : '');
        $tag_name_arr = [];
        if ($value) {
            $tag_name_arr = HouseSearchRoomnum::where('status', 'normal')->where('id', 'in', $value)->orderRaw('weigh desc,id desc')->column('name');
        }
        return count($tag_name_arr) > 0 ? implode(',', $tag_name_arr) : '';
    }
    public function getMobileTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['mobile']) ? $data['mobile'] : '');
        return $value ? str_replace(substr($value, 3, 4), '****', $value) : '';
    }

    // 来源:1=订阅动态,2=留电咨询,3=领取免费专车,4=帮你找房,5=咨询房价走势,6=领取优惠券,7=平台创建
    public function getTypeList()
    {
        return ['1' => __('订阅动态'), '2' => __('留电咨询'), '3' => __('领取免费专车'), '4' => __('帮你找房'), '5' => __('咨询房价走势'), '6' => __('领取优惠券'), '7' => __('平台创建')];
    }

    public function getSubscribeTypeList()
    {
        return ['0' => __('Subscribe_type 0'), '1' => __('Subscribe_type 1'), '2' => __('Subscribe_type 2'), '3' => __('Subscribe_type 3')];
    }

    public function getStateList()
    {
        return ['1' => __('State 1'), '2' => __('State 2'), '3' => __('State 3'), '4' => __('State 4')];
    }

    public function getGenderList()
    {
        return ['0' => __('Gender 0'), '1' => __('Gender 1'), '2' => __('Gender 2')];
    }

    public function getHouseStateList()
    {
        return ['0' => __('无意向'), '1' => __('待看房'), '2' => __('已看房'), '3' => __('已付订'), '4' => __('已签约'), '5' => __('已款清'), '6' => __('放弃客户')];
    }

    public function getAuditStateList()
    {
        return ['1' => __('Audit_state 1'), '2' => __('Audit_state 2'), '3' => __('Audit_state 3'), '4' => __('Audit_state 4')];
    }


    public function getHouseStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['house_state']) ? $data['house_state'] : '');
        $list = $this->getHouseStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getAuditStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['audit_state']) ? $data['audit_state'] : '');
        $list = $this->getAuditStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSubscribeTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['subscribe_type']) ? $data['subscribe_type'] : '');
        $list = $this->getSubscribeTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getGenderTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['gender']) ? $data['gender'] : '');
        $list = $this->getGenderList();
        return isset($list[$value]) ? $list[$value] : '';
    }




    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function userprofile()
    {
        return $this->belongsTo('UserProfile', 'user_id', 'user_id', [], 'LEFT')->setEagerlyType(0);
    }
    public function broker()
    {
        return $this->belongsTo('User', 'broker_user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }



    public function house()
    {
        return $this->belongsTo('House', 'house_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function rental()
    {
        return $this->belongsTo('Rental', 'rental_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    /**
     * 创建预约订单信息
     * @param int $type                         1    分类:1=订阅动态,2=留电咨询,3=领取免费专车,4=帮你找房,5=咨询房价走势
     * @param int $subscribe_type               0    订阅通知类型:0=无订阅,1=订阅变价通知,2=订阅开盘通知,3=订阅实时动态
     * @param int $house_id                     0    房源id
     * @param int $broker_user_id               0    关联经纪人id
     * @param string $mobile                    无   手机号
     * @param int $gender                       0    性别:0=未知,1=男,2=女
     * @param date $view_date                   无   看房时间
     * @param int $min_total_price              0    最低购房预算(万元)
     * @param int $max_total_price              0    最高购房预算(万元)
     * @param string $prov                      无   省
     * @param string $city                      无   省
     * @param string $region                    无   省
     * @param string $house_search_roomnum_ids  无   户型ids
     *  @param string $orther_areas             无   区县街道
     */
    public function createNowLog($params)
    {
        
        $exist = $this->where('user_id', $params['user_id'])->where('is_using', 2)->where('rental_id', 0)->find();
        if ($exist && $exist['broker_user_id']) {
            $broker_exist = User::find($exist['broker_user_id']);
            if (!$broker_exist) {
                $exist = null;
            }
        }
        $params['is_using'] = 1;
        if ($exist) {
            $params['broker_user_id'] = $exist['broker_user_id'];
            $params['state'] = 2;
        } else if (isset($params['broker_user_id']) && $params['broker_user_id'] > 0) {
            $params['is_using'] = 2;
            $params['state'] = 2;
            $this->where('user_id', $params['user_id'])->where('state', 1)->where('rental_id', 0)->update(['state' => 2]);
            $param['distributetime'] = time();
        }
        $res = $this->allowField(true)->save($params);
        if (!$res) {
            goto err;
        }
        
        // 更新房源的领取次数
        if ($params['type'] == 3 && isset($params['house_id']) && $params['house_id'] > 0) {
            $house_info = House::where('id', $params['house_id'])->find();
            if ($house_info) {
                $res = $house_info->save([
                    'receive_num' => $house_info['receive_num'] + 1,
                    'recievetime' => time()
                ]);
                if (!$res) {
                    goto err;
                }
            }
        }
        
        $user_info = UserProfile::where('user_id', $params['user_id'])->find();
        
        if ($params['is_using'] == 2) {
            $res = FollowLog::create([
                'user_id' => $params['user_id'],
                'broker_user_id' => $params['broker_user_id'],
                'appoint_log_id' => $this->id,
                'name' => '分配咨询师',
            ]);
            if (!$res) {
                goto err;
            }
            $user_info = UserProfile::where('user_id', $params['user_id'])->find();
            if ($user_info) {
                $save_data = [
                    'followtime' => time(),
                    'house_state' => 1,
                    'broker_user_id' => $params['broker_user_id']
                ];
                if ($user_info['user_type'] == 0) {
                    $save_data['user_type'] = 1;
                }
                $res = $user_info->save($save_data);
                if (!$res) {
                    goto err;
                }
            }
        } else if ($user_info['user_type'] == 0) {
            $save_data['user_type'] = 1;
            $res = $user_info->save($save_data);
            if (!$res) {
                goto err;
            }
        }
        
        return true;
        
        err:
        return false;
    }
    /**
     * 改变状态
     * 
     * @param int $user_id          -      用户id
     * @param int $changeStatus      1    改变方式：1=从客户公海里添加入我的客户，2=放弃客户,3=流失用户,4=已款清,5=其他（待看房，已看房，已付订，已签约）
     */
    public function change_appoint($user_id, $changeStatus = 1, $broker_user_id = 0, $appoint_log_id = 0)
    {
        switch ($changeStatus) {
            case 1:
                # 从客户公海里添加入我的客户
                if ($appoint_log_id) {
                    // 2、把该订单改为正在使用，并绑定经纪人
                    $res = $this->where('id', $appoint_log_id)->update(['is_using' => 2, 'broker_user_id' => $broker_user_id, 'distributetime' => time()]);
                    if (!$res) {
                        goto err;
                    }
                }
                // 3、把该客户的所有订单状态改为处理中
                $res = $this->where('user_id', $user_id)->where('state', 1)->update(['state' => 2]);
                if (!$res) {
                    goto err;
                }
                \app\common\model\xiluhouse\FollowLog::create([
                    'user_id' => $user_id,
                    'broker_user_id' => $broker_user_id,
                    'appoint_log_id' => $appoint_log_id,
                    'name' => '分配咨询师',
                ]);
                \app\common\model\xiluhouse\UserProfile::where('user_id', $user_id)->update(['followtime' => time(), 'house_state' => 1, 'broker_user_id' => $broker_user_id]);
                break;
            case 2:
                # 放弃客户
                if ($appoint_log_id) {
                    // 2、把该订单改为不使用，并解绑经纪人
                    $res = $this->where('id', $appoint_log_id)->update(['is_using' => 1, 'broker_user_id' => 0]);
                    if (!$res) {
                        goto err;
                    }
                }
                // 3、把该客户的所有订单状态改为待处理
                $res = $this->where('user_id', $user_id)->where('state', 2)->update(['state' => 1]);
                if (!$res) {
                    goto err;
                }
                \app\common\model\xiluhouse\UserProfile::where('user_id', $user_id)->update(['followtime' => time(), 'house_state' => 6, 'broker_user_id' => 0]);
                break;
            default:
                goto err;
                break;
        }
        return true;
        err:
        return false;
    }
}
